package photoMethod

import (
	// "fmt"
	"math"
	"os"
	"path/filepath"
	"photoPlugIn/config"
	"photoPlugIn/dbMethod"
	us "photoPlugIn/utils"

	"image"
	_ "image/gif"
	"image/jpeg"
	_ "image/png"

	"github.com/nfnt/resize"
)

var PHOTO_MINI = []string{"_mini_", "", ""}         //超小
var PHOTO_SMALL = []string{"_small_", "", ""}       //小型
var PHOTO_MEDIUM = []string{"_medium_", "", "1280"} //中等，名称、长、宽、

const DEFAULT_MAX_WIDTH float64 = 1920
const DEFAULT_MAX_HEIGHT float64 = 1920

//判断缓存数据库中是否记录了文件的MD5
func IsPhotoInCahce(md5, fileUrl string) {
	findValue := dbmethod.PhotoCahceFind(md5)

	if findValue.Id == 0 {
		//没有记录，将值插入
		// fmt.Println("findVlaue空,插入数值")
		_ = dbmethod.PhotoCahceInsert(md5)
	}
	//判断缓存文件夹中是否有缓存文件
	isPhotoCaheInFolder(md5, fileUrl)
}

func isPhotoCaheInFolder(md5, fileUrl string) {
	fileDirUrl := config.CONFIG.CacheDir + config.CONFIG.PHOTODB
	if fileDirUrl[len(fileDirUrl)-1:] != string(os.PathSeparator) { //判断获取的文件夹后面是否有/
		fileDirUrl = fileDirUrl + string(os.PathSeparator) //如果没有，添加/
	}
	filetzm := filepath.Ext(fileUrl)
	// fmt.Println("MD5名字", fileDirUrl+md5+filetzm)
	isFile, _ := us.PathExists(fileDirUrl+md5+filetzm, false)
	if !(isFile) {
		makeThumbnail(fileUrl, fileDirUrl+md5+filetzm)
	}

}

// 计算图片缩放后的尺寸
func calculateRatioFit(srcWidth, srcHeight int) (int, int) {
	ratio := math.Min(DEFAULT_MAX_WIDTH/float64(srcWidth), DEFAULT_MAX_HEIGHT/float64(srcHeight))
	return int(math.Ceil(float64(srcWidth) * ratio)), int(math.Ceil(float64(srcHeight) * ratio))
}

// 生成缩略图
func makeThumbnail(imagePath, savePath string) (string, error) {

	file, _ := os.Open(imagePath)
	defer file.Close()

	img, _, err := image.Decode(file)
	if err != nil {
		return "", err
	}

	b := img.Bounds()
	width := b.Max.X
	height := b.Max.Y

	w, h := calculateRatioFit(width, height)

	// fmt.Println("width = ", width, " height = ", height)
	// fmt.Println("w = ", w, " h = ", h)

	// 调用resize库进行图片缩放
	m := resize.Resize(uint(w), uint(h), img, resize.Lanczos3)

	// 需要保存的文件
	imgfile, _ := os.Create(savePath)
	defer imgfile.Close()

	// 以jpeg格式保存文件
	err = jpeg.Encode(imgfile, m, nil)
	if err != nil {
		return "", err
	}

	return "", nil
}

// 生成缩率图代码来源：https://www.jianshu.com/p/b0a18f2d005a
